import router from '@/router'
import store from '@/store'
import { getlocalstorage,removelocalstorage,setsessionstorage,getsessionstorage,removesessionstorage } from '@/components/js/Localstorage'
import {  asyncRouterMap,constantRouterMap } from '@/router'

import index from '@/components/Index'



router.beforeEach((to,from,next) => {
//	//console.log(to);
//	//console.log(from);
//	//console.log(next);


	
	let token = getsessionstorage("authorization");
	let sessionrole = getsessionstorage('role')
	let sessionroleinfo = JSON.parse(getsessionstorage('roleinfo'))
//	//console.log(sessionroleinfo)
	let username = getsessionstorage('username') 
	if(!token || !sessionrole || !sessionroleinfo || !username){
		if(to.path == '/login'){ 
			next()
		}else{
			next('/login')
		}
	}
	
	//如果没有动态路由表或者从登录页过来的->新建动态路由表
	if(!store.getters.dyrouter || from.path=='/login'){
		
		store.dispatch('setrole',sessionrole).then(()=>{
			store.dispatch('setroleinfo',sessionroleinfo).then(()=>{
			})
		})
		let dynamicrouter = [
			{name:"index",path: "/index",component: index,children:[]}
		];
		for(let i = 0;i < asyncRouterMap.length;i++){
			if(asyncRouterMap[i].hasOwnProperty('children')){
				for(let n = 0;n < asyncRouterMap[i].children.length;n++){
					if(/^[\u4e00-\u9fa5]/.test(asyncRouterMap[i].children[n].name)){
						for(let y in sessionroleinfo){
							if(asyncRouterMap[i].children[n].path == sessionroleinfo[y].path)
							dynamicrouter[0].children.push(asyncRouterMap[i].children[n])
						}
					}else{
						dynamicrouter[0].children.push(asyncRouterMap[i].children[n])
					}
				}
			}else{
				dynamicrouter.push(asyncRouterMap[i])
			}
		}
		store.dispatch('setdynamicrouter',dynamicrouter).then(()=>{
			
			router.addRoutes(store.getters.dyrouter);
		})
		
		
	}
	next()
})

